<?php
namespace app\admin\controller;

use app\admin\model\AdminMenu;
use app\admin\model\AdminRole;
use app\admin\model\AdminUser;
use app\admin\model\Order;
use app\admin\model\OrderFoods;
use app\admin\model\ShopCategory;
use app\admin\model\ShopFoods;
use app\admin\model\ShopList;
use app\admin\model\ShopTable;
use app\admin\model\Temporary;
use think\facade\Session;

class OrderController extends CommonController
{
    public function orderList(){
        return $this->fetch();
    }

    public function orderData($page,$limit){
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $where = input('param.order_no')?[['order_no','like','%'.input('param.order_no').'%']]:'';
        $data = Order::with(['user'=>function($query){
            $query->field('id,wx_nickname');
        },'shop'=>function($query){
            $query->field('id,shop_name');
        },'table'=>function($query){
            $query->field('id,table_no');
        }])->where($where)->where($shop_id)->page($page,$limit)->select()->each(function ($item){
            $item->user_id = $item->user->wx_nickname;
            $item->shop_id = $item->shop->shop_name;
            if ($item->table){
                $item->table_id = $item->table->table_no;
            }
            if (strtotime($item->pay_time) == strtotime("1970-01-01 08:00:00")){
                $item->pay_time = 1;
            }
        })->toArray();
        foreach ($data as $k=>$v){
            if (strtotime($v['pay_time']) == strtotime("1970-01-01 08:00:00")){
                $data[$k]['pay_time'] = '';
            }
            unset($v['user']);
            unset($v['shop']);
            unset($v['table']);
        }
        $count = Order::where($where)->where($shop_id)->count();
        $res = [
            'code'=>0,
            'msg'=>'返回成功',
            'count'=>$count,
            'data'=>$data
        ];
        return json($res);
    }

    public function remark(){
        $id = (int)input('post.id');
        $key = input('post.field');
        $value = input('post.value');
        $ret = Order::update([$key=>$value],['id'=>$id]);
        if (!$ret){
            return json(['code'=>0,'msg'=>'保存失败']);
        }
        return json(['code'=>1,'msg'=>'保存成功']);
    }

    public function foodList($order_no){
        $data['list'] = OrderFoods::with(['cook'=>function($query){
            $query->field('id,true_name');
        }])->where('order_no',$order_no)->select();
        foreach ($data['list'] as $k=>$v){
            $data['list'][$k]['image'] = $this->url.$v['image'];
            $data['list'][$k]['cook_id'] = $v['cook']['true_name'];
            if (!$data['list'][$k]['spec']){
                $data['list'][$k]['spec'] = '默认';
            }
            unset($data['list'][$k]['cook']);
        }
        $data['order_no'] = $order_no;
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $data['temporary'] = Temporary::where($shop_id)
            ->where('status',1)->field('id,food_name')->select()->toArray();
        $data['count'] = count($data['list']);
        $this->assign('data',$data);
        return $this->fetch();
    }

    public function foodReturn(){
        $id = input('post.id');
        $number = input('post.number');
        $food = OrderFoods::get($id);
        if ($number <= 0){
            return json(['code'=>0,'msg'=>'数量不能小于等于零']);
        }
        if ($number > $food['quantity']){
            return json(['code'=>0,'msg'=>'数量不能大于菜品数量']);
        }
        $num = $food['quantity'] - $number;
        $retNum = $food['return_number'] + $number;
        OrderFoods::update(['quantity'=>$num,'return_number'=>$retNum],['id'=>$id]);
        $total = OrderFoods::where('order_no',$food['order_no'])->field('quantity,food_price')->select();
        $arr = [];
        foreach ($total as $k=>$v){
            $arr[] = $v['food_price'] * $v['quantity'];
        }
        $total = array_sum($arr);
        Order::update(['money'=>$total,'cost'=>$total],['order_no'=>$food['order_no']]);
        return json(['code'=>1,'msg'=>'退回成功']);
    }

    public function confirm(){
        $shop_id = Session::get('shop_id')?['shop_id'=>Session::get('shop_id')]:"";
        $order_no = input('post.order_no');
        $table_no = input('post.table_no');
        $table = ShopTable::where($shop_id)->where('table_no',$table_no)->field('id')->find();
        if (!$table){
            return json(['code'=>0,'msg'=>'桌号不存在']);
        }
        $ret = Order::update(['order_status'=>1,'table_id'=>$table['id']],['order_no'=>$order_no]);
        if (!$ret){
            return json(['code'=>0,'msg'=>'核销失败']);
        }
        return json(['code'=>1,'msg'=>'核销成功']);
    }

    public function offPay(){
        $order_id = input('get.id');
        $order = Order::where('id',$order_id)->find();
        $shop = ShopList::where('id',$order['shop_id'])->field('shop_name')->find();
        $table = ShopTable::where('id',$order['table_id'])->field('table_no')->find();
        $data = Order::with(['orderFoods'=>function($query){
            $query->field('id,order_no,food_name,quantity,food_price');
        },'user'=>function($query){
            $query->field('id,wx_nickname');
        },'table'=>function($query){
            $query->field('id,table_no');
        }])->where('shop_id',$order['shop_id'])->where('table_id',$order['table_id'])
            ->where('pay_type',1)->where('pay_status',1)
            ->field('id,order_no,user_id,table_id,order_time,money')->order('order_time desc')->select()->toArray();
//        dump($data);die();
        $this->assign('data',$data);
        $this->assign('shop',$shop);
        $this->assign('table',$table);
        return $this->fetch();
    }

    //打折
    public function fracture(){
        $order_no = input('post.order_no');
        $type     = (int)input('post.type');
        $discount = (int)input('post.discount');
        $password = input('post.password');
        if (!$discount){
            return json(['code'=>0,'msg'=>'请输入折扣！']);
        }
        if (!$password){
            return json(['code'=>0,'msg'=>'请输入密码！']);
        }
        $user = AdminUser::where('id',Session::get('admin_id'))->find();
        $password = md5($user['username'].md5(trim($password)));
        if ($password != $user['password']){
            return json(['code'=>0,'msg'=>'密码错误！']);
        }
        $controller = request()->controller();
        $action  = request()->action();
        $menu_id = AdminMenu::where('controller',strtolower($controller))
            ->where('method',$action)->value('id');
        $rule = AdminRole::where('id',$user['role'])->find();
        $rule['rule'] = json_decode($rule['rule']);
        if (!in_array($menu_id,$rule['rule'])){
            return json(['code'=>0,'msg'=>'你没有权限！']);
        }
        $order = Order::where('order_no','in',$order_no)->select()->toArray();
        $status = [];
        foreach ($order as $k=>$v){
            if ($v['discount'] == 0){
                $status[]=true;
            }else{
                $status[]=false;
            }
        }
        if (in_array(false,$status)){
            return json(['code'=>0,'msg'=>'订单已有折扣！']);
        }
        if ($type == 1){
            foreach ($order as $k=>$v){
                $total = [];
                $orderFood = OrderFoods::where('order_no',$v['order_no'])->select()->toArray();
                foreach ($orderFood as $key=>$value){
                    $category_id = ShopFoods::where('id',$value['food_id'])->value('category_id');
                    $category = ShopCategory::where('id',$category_id)->value('discount');
                    if ($category){
                        $total[] = round(($value['food_price'] * $value['quantity'])*($discount/100),2);
                    }else{
                        $total[] = $value['food_price'] * $value['quantity'];
                    }
                }
                $upData = [
                    'money'=>array_sum($total),
                    'discount'=>($discount/10).'折'
                ];
                Order::update($upData,['id'=>$v['id']]);
            }
        }elseif($type == 2){

        }
        return json(['code'=>1,'msg'=>'打折成功']);
    }

    public function orderAddTemp(){
        $order_no = input('post.order_no');
        $food_id  = input('post.food_id');
        $number  = input('post.number');
        if (!$food_id){
            return json(['code'=>0,'请至少选择一道菜！']);
        }
        if (!$number){
            return json(['code'=>0,'数量不能为空！']);
        }
        $order = Order::where('order_no',$order_no)->find();
        $temp = Temporary::where('id','in',$food_id)->select()->toArray();
        $image = ShopList::where('id',Session::get('shop_id'))->value('shop_image');
        $total = [];
        foreach ($temp as $key=>$value){
            if ($number[$value['id']]){
                $data = [
                    'user_id'=>$order['user_id'],
                    'order_no'=>$order['order_no'],
                    'father_no'=>$order['order_no'],
                    'food_name'=>$value['food_name'],
                    'image'=>$image?$image:'',
                    'quantity'=>$number[$value['id']],
                    'food_price'=>$value['price']
                ];
                OrderFoods::create($data);
                $total[] = $data['food_price'] * $data['quantity'];
            }
        }
        $total = array_sum($total);
        Order::update(['money'=>$order['money']+$total,'cost'=>$order['cost']+$total],['id'=>$order['id']]);
        return json(['code'=>1,'msg'=>'添加成功']);
    }

    public function offPayDo(){
        $order_no = input('post.order_no');
        $order = Order::where('order_no','in',$order_no)->select()->toArray();
        foreach ($order as $key => $value){
            Order::update(['pay_status'=>2,'pay_time'=>time()],['id'=>$value['id']]);
            $ret = $this->waiter($value['table_id'],$value['order_no']);
        }
        return json(['code'=>1,'msg'=>'结算成功']);
    }




}